<?php

class CronController extends Controller
{
	public function actionSitemap()
	{
		return $this->render('sitemap');
	}

	public function actionGoodsParser()
	{
//        $this->_saveRow(array('url'=>'', 'vendor'=>'Converse'), array(), array());
//        exit;

		set_time_limit(60000);
		$oStoreUrl = new StoreUrl();
		$oGrabber = new Grabber();
        $oCategories = new Categories();
        $oCategoryRowset = $oCategories->order('id ASC')->findAllByAttributes(array(), "type='goods' AND parser_id > 0 AND store_url !=''");
        $aCategories = array();
        foreach($oCategoryRowset as $aRow)
            $aCategories[$aRow->id] = $aRow;


		$aRowset = $oStoreUrl->limit(10)->order('id DESC')->findAllByAttributes(array(
//			'is_parsed' => 0,
		), '(url = data AND is_parsed=1) OR (is_parsed = 0)');
//print_r($aRowset); exit;
		$aUrl = array();
		foreach($aRowset as $row)
		{
			$aUrl[$row->url] = $row;
            $aUrl[$row->url]->is_parsed = 1;
            $aUrl[$row->url]->save();
		}
//        print_r($aUrl); exit;

		if(!$aUrl)
			exit;
//        print_r($aUrl); exit;
		$aRowset = $oGrabber->getRow('SixPM', array_keys($aUrl));
//		print_r($aRowset); exit;

		$oGoods = new Goods();
		foreach($aRowset as $url => $aRow)
		{
//			print_r($aRow); exit;
			if(!empty($aUrl[$url]) && is_object($aUrl[$url]))
			{
				$aUrl[$url]->is_parsed = 1;
				$aUrl[$url]->is_new = 1;
				$aUrl[$url]->data = json_encode($aRow);
				$aUrl[$url]->save();
			}

            $aRow['url'] = $url;

			if(empty($aRow['photos']))
				continue;

//			$oGoods->saveParsedRow($aRow, $aUrl, $aCategories);
		}

        exit;
	}

    protected function _saveRow($aRow, $aUrl, $aCategories = array())
    {
        $oGoods = new Goods();
        $oGoodsRow = $oGoods->findByAttributes(array(
            'original_url' => $aRow['url']
        ));

//	    print_r($aRow); exit;

        $oPropertyValue = new PropertyValue();
        $oPropertyValue = $oPropertyValue->findByValue($aRow['vendor'], 5);

        $isNewRow = false;
        if(!$oGoodsRow)
        {
            $oGoodsRow = new Goods();

            $title = $aRow['vendor'].' '.$aRow['title'];
            $alias = $oGoodsRow->generateAlias(($oGoodsRow && $oGoodsRow->id ? $oGoodsRow->id : null), $title);

            $oGoodsRow->setAttributes(array(
                'category_id' => $aUrl[$aRow['url']]['category_id'],
                'parser_id' => $aUrl[$aRow['url']]['parser_id'],
                'title' => $title,
                'original_title' => $title,
                'alias' => $alias,
                'category_alias' => !empty($aCategories[$aUrl[$aRow['url']]['category_id']]) ? $aCategories[$aUrl[$aRow['url']]['category_id']]->alias : '',
                'short_description' => String::substr(String::stripTagsAttributes($aRow['description']), 200),
                'description' => String::stripTagsAttributes($aRow['description'], '<img><p><span><ul><ol><li><div><dl><dt><dd>'),
                'original_description' => $aRow['description'],
                'price' => $aRow['price'],
                'user_add' => 1,
                'date_add' => date('Y-m-d H:i:s'),
                'original_url' => $aRow['url'],
                'active' => 1,
                'is_available' => 1,
                'is_new' => 0,
                'quantity' => 1,
                'sort' => 0,
                'status' => 1,
            ));

            $isNewRow = true;
//                print_r($oGoodsRow); exit;
        }

        $oGoodsRow->price = $aRow['price'];

        if($oGoodsRow->save(true) && $isNewRow)
        {
            $oGoodsRow->color_bind = $oGoodsRow->getPrimaryKey();
            $oGoodsRow->save();
        }

        if(!empty($oPropertyValue) && !empty($oGoodsRow) && $oGoodsRow->getPrimaryKey() > 0)
        {
            $oGoodsProperty = new GoodsProperty();

            $oGoodsProperty->setAttributes(array(
                'goods_id' => $oGoodsRow->getPrimaryKey(),
                'property_id' => $oPropertyValue->property_id,
                'value_id' => $oPropertyValue->id
            ));

            $oGoodsProperty->save();
        }

        if(false && !empty($aRow['photos']) && $oGoodsRow)
        {
            $i = 0;
            foreach($aRow['photos'] as $imgSrc)
            {
                $oPhoto = new Photos();
                $oPhoto = $oPhoto->findByAttributes(array('original_url' => $imgSrc));

                if($oPhoto && $oPhoto->id > 0)
                    continue;

                $oThumb = new Thumbnail($imgSrc);
                $result = $oThumb->crop('/-/', Yii::app()->params->photos[$oGoodsRow->getTableName()], $oGoodsRow->alias, $oGoodsRow->getPrimaryKey());

                if($result)
                {
                    $oPhoto = new Photos();
                    $oPhoto->attributes = array(
                        'target_type' => $oGoodsRow->getTableName(),
                        'target_id' => $oGoodsRow->getPrimaryKey(),
                        'path' => $result['dir'],
                        'file' => $result['file'],
                        'upload_user' => 1,
                        'upload_time' => time(),
                        'is_main' => ($i++ == 0 ? 1 : 0),
                        'original_url' => $imgSrc
                    );
                    $oPhoto->save();
                }
	            else
	            {
		            $oGoodsRow->delete();
	            }
            }
        }
    }

	public function actionNewGoods()
	{
        $oParser = new Parser();
        $oCategories = new Categories();
        $oCategoryRow = $oCategories->findByAttributes(array(), "parser_id > 0 AND is_parsed = 0 AND store_url !=''");

        if(!$oCategoryRow)
        {
            $oCategories->updateAll(array('is_parsed' => 0), "parser_id > 0 AND is_parsed = 1 AND store_url !=''");
            exit;
        }

        $oParserRow = $oParser->findByPk($oCategoryRow->parser_id);

//		$oStoreUrl = new StoreUrl();
//		$oStoreUrl->updateAll(array('is_new' => '0'), "category_id = ". $oCategoryRow->id ." AND is_new = 1");
//		print_r($oParserRow); exit;

		set_time_limit(60000);

		$oGrabber = new Grabber();
//		 = ;
//		print_r($aRowset); exit;

		foreach($oGrabber->getRowset($oParserRow['class'], $oCategoryRow['store_url'], true) as $aRowset)
		{
//            print_r($aRowset); exit;
			foreach($aRowset as $url => $aData)
			{
				try
				{
					$oStoreUrl = new StoreUrl();
					$oStoreUrl = $oStoreUrl->findByAttributes(array('url' => $url));
					if(!empty($oStoreUrl) && $oStoreUrl->id > 0)
						continue;

					$oStoreUrl = new StoreUrl();
					$oStoreUrl->setAttributes(array(
						'url' => $url,
					    'data' => $aData,
					    'category_id' => $oCategoryRow->id,
					    'parser_id' => $oParserRow->id,
					    'time' => time(),
					    'is_new' => 1,
					));
					$oStoreUrl->save();

//					echo time().'<br />';
					unset($oStoreUrl);
				}
				catch(Exception $e)
				{}
			}
		}

        $oCategoryRow->is_parsed = 1;
        $oCategoryRow->save();

		//print_r($aRowset);


		Yii::app()->end();
	}

	public function actionParser()
	{
        set_time_limit(6000);

//        echo Yii::app()->params->photos['goods']['-'];

        $oGrabber = new Grabber();

        $oRowset = $oGrabber->getRowset('Aliexpress', 'GoodsParserRow', true);
//        print_r($oRowset); exit;
//
        foreach($oRowset as $oRow)
        {
            $oRow = $oGrabber->getRow('Aliexpress', 'GoodsParserRow', $oRow->url);
//            $oRow = $oGrabber->getRow('Aliexpress', 'GoodsParserRow', 'http://www.aliexpress.com/item/Ultrathin-Aluminum-Alloy-Bluetooth-Wireless-Keyboard-For-IPad-2-3-Black-white/850769351.html');

            $oGoods = new Goods();
            $oGoodsRow = $oGoods->findByAttributes(array('original_url' => $oRow->url));

            if(!empty($oGoodsRow))
            {
                $oGoods = $oGoodsRow;
                $oGoods->attributes = array(
                    'original_title' => $oRow->getTitle(),
                    'original_description' => $oRow->getDescription(),
                    'price' => $oRow->getPrice(),
                    'user_edit' => 1,
                    'date_edit' => date('Y-m-d H:i:s'),
                );
            }
            else
            {
                $oGoods = new Goods();
                $oGoods->attributes = array(
                    'category_id' => 7,
                    'title' => $oRow->getTitle(),
                    'original_title' => $oRow->getTitle(),
                    'alias' => ($oRow->getTitle() ? strtolower(Transliteration::text($oRow->getTitle())) : ''),
                    'short_description' => String::substr(String::stripTagsAttributes($oRow->getDescription()), 200),
                    'description' => String::stripTagsAttributes($oRow->getDescription(), '<img><p><span><ul><ol><li><div><dl><dt><dd>'),
                    'original_description' => $oRow->getDescription(),
                    'price' => $oRow->getPrice(),
                    'user_add' => 1,
                    'date_add' => date('Y-m-d H:i:s'),
                    'original_url' => $oRow->url,
                );
            }

            if($oGoods->save(false) && $oRow->photo)
            {
                $oPhoto = new Photos();
                $oPhoto = $oPhoto->findByAttributes(array('original_url' => $oRow->photo));

                if(!($oPhoto && $oPhoto->id > 0))
                {
                    $oThumb = new Thumbnail($oRow->photo);
                    $result = $oThumb->crop('/img/-/', Yii::app()->params->photos['goods'], strtolower(Transliteration::text($oRow->getTitle())), $oGoods->getPrimaryKey());

                    if($result)
                    {
                        $oPhoto = new Photos();
                        $oPhoto->attributes = array(
                            'target_type' => 'goods',
                            'target_id' => $oGoods->getPrimaryKey(),
                            'path' => $result['dir'],
                            'file' => $result['file'],
                            'upload_user' => 1,
                            'upload_time' => time(),
                            'is_main' => 1,
                            'original_url' => $oRow->photo
                        );
                        $oPhoto->save(true);
                    }

//                    echo '<img alt="" src="'. $result['dir'] .''. $result['file'] .'" />';
                }

                if($oRow->getPhotos())
                {
                    foreach($oRow->getPhotos() as $imgSrc)
                    {
                        if($imgSrc == $oRow->photo)
                            continue;

//                        echo $imgSrc;
//                        echo '<br> length: '.strlen($imgSrc); exit;

                        $oPhoto = new Photos();
                        $oPhoto = $oPhoto->findByAttributes(array('original_url' => $imgSrc));

                        if($oPhoto && $oPhoto->id > 0)
                            continue;

                        $oThumb = new Thumbnail($imgSrc);
                        $result = $oThumb->crop('/img/-/', Yii::app()->params->photos['goods'], strtolower(Transliteration::text($oRow->getTitle())), $oGoods->getPrimaryKey());

                        if($result)
                        {
                            $oPhoto = new Photos();
                            $oPhoto->attributes = array(
                                'target_type' => 'goods',
                                'target_id' => $oGoods->getPrimaryKey(),
                                'path' => $result['dir'],
                                'file' => $result['file'],
                                'upload_user' => 1,
                                'upload_time' => time(),
                                'is_main' => 0,
                                'original_url' => $imgSrc
                            );
                            $oPhoto->save(false);
                        }

//                        echo '<img alt="" src="'. $result['dir'] .'list-'. $result['file'] .'" />';
                    }
                }
            }

            print_r($oRow->getPhotos());
            echo '<br />'; //exit;
        }

        exit;


        Yii::app()->end();
	}

    public function actionCurrencies()
    {
        set_time_limit(6000);

        $oGrabber = new Grabber();

        $oRowset = $oGrabber->getRowset('Privatbank', 'CurrencyParserRow');

        foreach($oRowset as $oRow)
        {
            $oCurrencies = new Currencies();

            $oCurrencies->setAttributes(array(
                'title' => $oRow->title,
                'short' => $oRow->short,
                'rate' => $oRow->rate,
                'date' => date('Y-m-d H:i:s'),
            ));

            $oCurrencies->save();
        }

        exit;
    }

    public function actionUpdatePrice()
    {
        // Витягуємо поточний активний парсер
        $oParser = new Parser();
        $oCriteria = $oParser->getDbCriteria();
        $oCriteria->order = 'id ASC';
        $oCriteria->addCondition('enabled = 1')->addCondition('active = 1');
        $oRow = $oParser->find($oCriteria);

        // Якщо немає парсера, включаємо перший в списку включених
        if(!$oRow)
        {
            $oCriteria = $oParser->getDbCriteria();
            $oCriteria->order = 'id ASC';
            $oCriteria->addCondition('enabled = 1');
            $oRow = $oParser->find($oCriteria);
            $oRow->active = 1;
            $oRow->save();
        }

        // Якщо витягли парсер то підключаємо його
        if($oRow)
        {
            $oParser = $oRow;
            $oGrabber = new Grabber();
            $oGoods = new Goods();

            $this->oPager->setCurrentPage(($oParser->page >= 0 ? $oParser->page : 0));
            $this->oPager->setPageSize(5);

            $oGoodsRowset = $oGoods->getList(null, $this->oPager, array(
                'order' => 'id ASC',
                'parser_id' => $oParser->id
            ));

            foreach($oGoodsRowset as $oGoods)
            {
                if($oGoods->original_url)
                {
	                echo $oGoods->id."<br>";
	                echo $oGoods->original_url."<br>";
                    $oPriceRow = $oGrabber->getRow($oParser->class, 'PriceParserRow', $oGoods->original_url);
	                if(!$oPriceRow)
	                {
		                $oGoods->status = 0;
		                $oGoods->save();

		                continue;
	                }

	                $oPriceRow = $oPriceRow->getArray();

//	                print_r($oPriceRow); exit;

                    // Оновлюємо ціну товару
                    if($oPriceRow && !empty($oPriceRow['price']))
                    {
	                    $oGoods->old_price = 0;
	                    if($oGoods->price > $oPriceRow['price'])
		                    $oGoods->old_price = $oGoods->price;

                        $oGoods->price = $oPriceRow['price'];
	                    if(!empty($oPriceRow['msrp']))
                            $oGoods->msrp = $oPriceRow['msrp'];

                        $oGoods->save();

	                    // оновлюємо кількість товарів по розміру
	                    if(!empty($aPriceRow['sizes']))
	                    {
		                    $oGoodsProperty = new GoodsProperty();
		                    $oValues = $oGoodsProperty->getListByStoreId(array_keys($aPriceRow['sizes']), $oGoods->id);

		                    if(!empty($oValues))
		                    {
			                    foreach($oValues as $oValue)
			                    {
				                    if(!empty($aPriceRow['sizes'][$oValue->stock_value_id]))
				                    {
					                    $oValue->count = $aPriceRow['sizes'][$oValue->stock_value_id];
					                    $oValue->save();
				                    }
			                    }
		                    }
	                    }
                    }
                    else
                    {
                        echo 'Не пропарсився товар: '. $oGoods->id;
                        echo '<br />';
                    }
                }
            }

            // Якщо пропарсили всі товари
            if($this->oPager->getCurrentPage() + 1 >= $this->oPager->getPageCount())
            {
//                print_r($oParser); exit;
                $oParser->page = 0;
                $oParser->active = 0;
                $oParser->save();

                // Вибираємо наступний парсер і активуємо його
                $oNextParser = new Parser();

                $oCriteria = $oNextParser->getDbCriteria();
                $oCriteria->order = 'id ASC';
                $oCriteria->addCondition('enabled = 1')->addCondition('id > '. $oParser->id);

                $oNextParser = $oNextParser->find($oCriteria);

                if($oNextParser)
                {
                    $oNextParser->active = 1;
                    $oNextParser->page = 0;
                    $oNextParser->save();
                }
            }

            // Інакше ставимо наступну сторінку
            else
            {
                $oParser->page = $oParser->page + 1;
                $oParser->save();
            }
        }

        $oGrabber = new Grabber();



        exit;
    }

}